package br.com.localfloripa.dao;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Named;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.localfloripa.entities.Estado;
import br.com.localfloripa.entities.Municipio;
import br.com.localfloripa.entities.Servico;


@Named("servicoDao")
public class ServicoDao extends DaoManager<Servico> {
	
	private static final Logger log = LoggerFactory.getLogger(ServicoDao.class);	
	private static final Integer MAX_ROWS = 15; 
	
	public Servico findById(Long idServico) throws Exception {
		return em.find(Servico.class, idServico);
	}
	
	public List<Servico> listServicosOrdemNome() throws Exception {
		
		Query query = em.createQuery("SELECT s FROM Servico s WHERE s.ativo IS TRUE ORDER BY s.nome");
		return query.getResultList();		
	}
	
	public List<Servico> listServicosOrdemNovos() throws Exception {
		
		Query query = em.createQuery("SELECT s FROM Servico s WHERE s.ativo IS TRUE ORDER BY s.id ASC");
		query.setMaxResults(MAX_ROWS);
		return query.getResultList();
	}
	
	public List<Servico> listServicosPaginada(int first,int pageSize) throws Exception {
		
		Query query = em.createQuery("SELECT s FROM Servico s ORDER BY s.nome");
		query.setFirstResult(first);
		query.setMaxResults(pageSize);		
		return query.getResultList();
	}
	
	public Long countListServicos() {
		Query query = em.createQuery("SELECT COUNT(s.id) FROM Servico s");
		return (Long) query.getSingleResult();
	}
	
	public List<Servico> maxServicosByAnuncio(Estado estado) throws Exception {
		
		Query query = em.createQuery("SELECT s,COUNT(s.id) FROM Servico s JOIN s.anuncios as a WHERE a.empresa.endereco.municipio.estado.id = :idEstado " +
				"AND a.ativo IS TRUE AND a.cliente.ativo IS TRUE AND s.ativo IS TRUE " +
				"GROUP BY s.id,s.ativo,s.nome,s.descricao ORDER BY COUNT(s.id) DESC");
		query.setParameter("idEstado", estado.getId());
		query.setMaxResults(5);	
		List<Servico> servicos = new ArrayList<Servico>();
		List objects = query.getResultList();
		if (objects != null) {
			for (int i = 0; i < objects.size(); i++) {
				Object[] arrayObject = (Object[]) objects.get(i);
				servicos.add((Servico)arrayObject[0]);							
			}
		}						
		return servicos;
	}

}


